import json
import traceback

from fastapi import APIRouter
from re_common.baselibrary.tools.myparsel import MParsel
from re_common.baselibrary.utils.basedict import BaseDicts
from re_common.baselibrary.utils.core.mlamada import bools_string
from re_common.baselibrary.utils.core.requests_core import MsgCode

from apps.core.callback import default_call_back
from apps.core.m_route import ContextIncludedRoute
from apps.core.return_info import ReturnInfo
from apps.crawler_platform.core_platform.g_model import InputPlatformModel, ParaAllModel

router = APIRouter(route_class=ContextIncludedRoute)


@router.post("/para/para_all")
async def para_all(input: InputPlatformModel[ParaAllModel]):
    """
    通用解析html方法,包含css和xpath解析
    :param input:
    :return:
    """
    return_info = ReturnInfo()
    return_info.msg_code = 200
    parse_dict = input.data.parse_dict
    re_dict = {}
    flag = bools_string(True)
    msg = "解析成功"
    try:
        for key, val in parse_dict.items():
            parse_dict = val.parse_dict
            html_model = val.html_model
            html = html_model.html
            call_back = val.call_back
            mc = MParsel(html=html)
            new_dict = {}
            if parse_dict["type"] == "CSS":
                new_dict = mc.css_parsel(sel=mc.sel, css_selector=parse_dict["rules"])
                BaseDicts.get_recursive_dict(new_dict, None, default_call_back)
            elif parse_dict["type"] == "XPATH":
                new_dict = mc.xpath_parsel(sel=mc.sel, xpath_selector=parse_dict["rules"])
                BaseDicts.get_recursive_dict(new_dict, None, default_call_back)
            elif parse_dict["type"] == "JSON":
                new_dict = json.loads(html)
            elif parse_dict["type"] == "HTML":
                new_dict = html_model.dict()
            if call_back and call_back != "":
                BaseDicts.get_recursive_dict(new_dict, None, eval(call_back))
            re_dict[key] = new_dict
    except:
        return_info.status = bools_string(False)
        return_info.msg_code = MsgCode.PARE_STRUCTURE_ERROR
        return_info.msg = "解析失败"
        return_info.data = {"err_except": traceback.format_exc()}
        return return_info.todict()
    return_info.status = flag
    return_info.msg = msg
    return_info.data = re_dict
    return return_info.todict()

# @router.post("/para/para_css")
# async def para_css(input: InputPlatformModel[CSSParaModel]):
#     return_info = ReturnInfo()
#     css_dicts = input.data.css_dicts
#     re_dict = {}
#     for key,val in css_dicts.items():
#         parse_rule = val["parse_rule"]
#         html = val["html"]
#         call_back = val["call_back"]
#         mc = MParsel(html=html)
#         new_dict = mc.css_parsel(sel=mc.sel, css_selector=parse_rule)
#         if call_back and call_back != "":
#             BaseDicts.get_recursive_dict(new_dict, None, call_back)
#         re_dict[key] = new_dict
#     return_info.status = bools_string(True)
#     return_info.msg_code = 200
#     return_info.msg = ""
#     return_info.data = re_dict
#     return return_info.todict()
